package cn.jimu98.schedules;

import cn.jimu98.entity.Post;
import cn.jimu98.service.PostService;
import cn.jimu98.util.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Classname ViewCountAsyTask
 * @Description TODO
 * @Date 2020/6/10 15:38
 * @Created by kaibo
 */
@Component
public class ViewCountAsyTask {
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    PostService postService;

    @Scheduled(cron ="0/5 * * * * *")//每分钟同步
    public void task() {
        Set<String> keys = redisTemplate.keys("rank:post:*");
        List<String> ids = new ArrayList<>();
        for (String key : keys) {
            if(redisUtil.hHasKey(key,"post:viewCount")){
                ids.add(key.substring("rank:post:".length()));
            }
        }
        if(ids.isEmpty())return;

        //需要更新阅读量
        List<Post> list = postService.list(new QueryWrapper<Post>().in("id", ids));
        if(list.isEmpty())return ;
        for (Post post : list) {
            Integer viewCount = (Integer) redisUtil.hget("rank:post:" + post.getId(), "post:viewCount");
            post.setViewCount(viewCount);
        }
        boolean isSucc = postService.updateBatchById(list);

        if(isSucc){
            for (String id : ids) {
                redisUtil.hdel("rank:post:"+id,"post:viewCount");
                System.out.println("同步成功");
           }
        }
    }
}
